import config from '@/config'
import { useUserStoreToRefs } from '@/store/useUserStore'
import { logOut } from '@/hooks/useLogin'
let exists = false
export default function (param) {
	const {access_token} = useUserStoreToRefs()
	let url = param.url,
		method = param.method,
		header = {},
		data = param.data || "",
		prefix = param.prefix || 'api'
	const requestUrl = config.api + `/${prefix}` + url
	let flowIdHeader = {
		'x-flow-id': new Date().getTime(),
		"x-client-id": ""
	};
	Object.assign(header, flowIdHeader)
	const token = access_token.value || ""
	let tokenValue = token ? 'Bearer ' + token : 'Basic bWFsbC1hcHA6bWFsbC1hcHA=';
	if(param.isNotToken){
		tokenValue = 'Basic bWFsbC1hcHA6bWFsbC1hcHA='
	}
	const target = {
		Authorization: tokenValue
	}
	Object.assign(header, target)
	let params = {
		url: requestUrl,
		method: method,
		header: header,
	}
	if (data) {
		Object.assign(params, { data: data })
	}
	return new Promise((resolve, reject) => {
		try {
			uni.request(params).then(res => {
				if (res.statusCode == 401) {
					console.log(param)
					console.log(exists)
					if (!exists) {
						exists = true
						//多次执行时，如当前页面就是登录页面则不进行跳转
						const pages = getCurrentPages()
						const currentPage = pages[pages.length - 1]
						const currentRoute = currentPage.route
						console.log(currentRoute)
						if (currentRoute != 'pages/login/index') {
							// param.isExecute设置401状态下是否弹框提示
							if(param.isExecute !== false){
								uni.showModal({
									content: '令牌已失效，请重新登录',
									confirmText: '确定',
									showCancel: false,
									success: (res) => {
										if (res.confirm) {
											exists = false
											// console.log(exists)
											logOut()
										}
									}
								})
							}else{
								resolve(res.data)
								exists = false
								uni.hideLoading()
							}
							
						}
					}

					return
				}
				resolve(res.data)

			}).catch(err => {
				console.log("错误", err)
				if(err.errMsg.indexOf('statusCode:-1')>-1){
					uni.showToast({
						icon:'none',
						title:'无法链接到网络，请检查网络设置 '
					})
				}
				
			})
		} catch (err) {
			console.log("catch", err)
		}
	})
}